var submitForm = function (showType, submitBtn, isAjax) {
    $("#J_form").Validform({
        btnSubmit: submitBtn,
        ajaxPost: isAjax,
        //msg：提示信息;
        //o:{obj:*,type:*,curform:*},
        //obj指向的是当前验证的表单元素（或表单对象，验证全部验证通过，提交表单时o.obj为该表单对象），
        //type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态,
        //curform为当前form对象;
        //cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
        tiptype: function (msg, o, cssctl) {
            if (showType == 1) {
                if (!o.obj.is("form")) { //验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
                    $('.Validform_checktip').remove();
                    o.obj.parent().append('<span class="Validform_checktip"></span>');
                    var objtip = o.obj.siblings(".Validform_checktip");
                    cssctl(objtip, o.type);
                    objtip.text(msg);
                }
            } else if (showType == 2) {
                if (o.type == 3) {
                    return showMiniModal(msg);
                }
            }
        },
        callback: function (data) {
            showMiniModal(data.msg, data.code, data.url);
            if (data.code == 1) setTimeout('window.location.href="' + url + '"', 3000);
            console.log(data);
        }
    });
}

//弹出窗
var showMiniModal = function (msg, code, url, onclick) {
    if($('#J_mini_modal').html() == undefined){
        if(confirm(msg)) {
            location.href=url;
        }
    }else{
        $('#J_mini_modal .modal-body').html(msg);
        $('#J_mini_modal').modal('show');
        if(onclick) $('#J_mini_modal .J_ok').attr('onclick', onclick);
        if (code == 1) $('#J_mini_modal .J_ok').attr('data-url', url);
    }
    return false;
}

//清除input数据
$('.J_del_input').click(function () {
    var id = $(this).attr('data-id');
    $('#'+id).val('');
});

var J_file_type = function (_this) {
    var val = $(_this).val(), html = '';
    switch (val) {
        case 'text':
            html = '<input type="text" class="input-txt" name="fieldValue[]" />';
            break;
        case 'select':
            html = '<textarea class="tarea" name="fieldValue[]" placeholder="select初始值 多个值换行区分\n例如 (默认值 default,不写默认第一个) \n男\n女\ndefault:女"></textarea>';
            break;
        case 'textarea':
            html = '<textarea class="tarea" name="fieldValue[]"></textarea>';
            break;
        case 'radio':
            html = '<textarea class="tarea" name="fieldValue[]" placeholder="radio初始值 多个值换行区分\n例如 (默认值 default,不写默认第一个) \n男\n女\ndefault:女"></textarea>';
            break;
        case 'hidden':
            html = '<input type="text" class="input-txt" name="fieldValue[]" placeholder="用于范围修改时"/>';
            break;
        case 'file':
            html = '<input type="file" class="input-txt" name="fieldValue[]"/>';
            break;
        case 'checkbox':
            html = '<textarea class="tarea" name="fieldValue[]" placeholder="checkbox初始值 多个值换行区分\n例如 (默认值 default,不写默认第一个) \n男\n女\ndefault:女"></textarea>';
            break;
    }

    $(_this).prev('div').html(html);
}
//删除数据
var J_del = function(_this){
    var __this = $(_this), _url, _msg, _onclick;
    _url = __this.attr('data-url');
    _msg = __this.attr('data-msg');
    _onclick = __this.attr('data-click');
    if(_url) showMiniModal(_msg ? _msg : '是否确定删除该数据', 1, _url, _onclick);
}

//删除层
var J_del_div = function(_this){
    var __this = $(_this), _url, _val;
    _class = __this.attr('data-class');
    _msg = __this.attr('data-msg');
    if(confirm(_msg ? _msg : "您确定要删除此条记录？")){
        $(_this).parents('.'+_class).remove();
    }
}

//赋值
var J_put_val = function(_this){
    $(_this).next().val($(_this).find('input').is(':checked'));
}

//分类
var article = function(_this, data){
    var _article = _this.attr('data-article'),
        art_html = $('.'+_article ).html(),
        html = '',
        _class = _this.attr('data-class');
    var json = data.data.list;
    if(json != undefined &&  json != '')
        $.each(json, function(i, obj) {
            html += art_html.replace(/__cat_icon__/g, obj.cat_icon)
                .replace(/__cat_name__/g, obj.cat_name)
                .replace(/__cat_link__/g, obj.cat_link)
                .replace(/__cat_desc__/g, obj.cat_desc)
                .replace(/__title__/g, obj.title)
                .replace(/__thumb__/g, obj.thumb)
                .replace(/__article_id__/g, obj.article_id)
                .replace(/__click__/g, obj.click)
                .replace(/__comment__/g, obj.comment)
                .replace(/__add_time__/g, obj.add_time)
                .replace(/__download__/g, obj.download?obj.download:0)
                .replace(/__description__/g, obj.description)
                .replace(/__keywords__/g, obj.keywords)
                .replace(/__link__/g, obj.link)
                .replace(/__cat_id__/g, obj.cat_id);
            if(typeof articleItemBack == "function"){
                html = articleItemBack(_this, html, obj);
            }
        });
    $('.'+_class).html(html);
}


// function articleItemBack(_this, html, obj) {
//     html = html.replace(/__time__/g, obj.time)
//             .replace(/__browse__/g, obj.browse);
//     return html;
// }
var J_loade = function(__this){
    var _this = $(__this),
        _url = _this.attr('data-url'),
        _article = _this.attr('data-article'),
        _class = _this.attr('data-class'),
        _method = _this.attr('method');
    _this.siblings().removeClass('active');
    _this.addClass('active');
    if(_url == '' || _url == 'undefined') return false;
    if(_method != '' && _method != 'undefined' && _method == 'post'){
        $.post(_url, function (data) {
            //回调方法
            if(typeof loadeBack== "function"){
                loadeBack(_this, data);
            }

            //分类
            if(_article != undefined && _article != ''){
                article(_this, data);
            }
        }, 'json');
    } else{
        $.get(_url, function (data) {
            //回调方法
            if(typeof loadeBack== "function"){
                loadeBack(_this, data);
            }
            //分类
            if(_article != undefined && _article != ''){
                article(_this, data);
            }
        });
    }

}

//ajax分页
var page = function(_this, data, url, div){
    var li = '', active = '', j=1, _url='', listRows=0, json = data.data;
    listRows =  parseFloat(parseInt(json.count) /  parseInt(json.listRows));
    if(listRows % 1 > 0) listRows = parseInt(listRows) +1;
    $('.'+div).html('');
    if(listRows <= 1) return false;
    //上一页
    if(parseInt(json.page - 1) > 0) _url = url.replace('__page__', parseInt(json.page - 1)).replace('__listRows__', json.listRows);
    li = '<li onclick="J_loade(this)" data-article="J_article" data-class="J_home" data-url="'+_url +'">'
        +'  <a href="javascript:;" aria-label="Previous">'
        +'   <span aria-hidden="true">上一页</span>'
        +' </a>'
        +'</li>';

    for(var i=1; i<=listRows; i++){
        active = '', _url='';
        if(i == json.page) active = 'active';
        else _url = url.replace('__page__', i).replace('__listRows__', json.listRows);
        li += '<li class="'+active+'" onclick="J_loade(this)" data-article="J_article" data-class="J_home" data-url="'+_url +'">'
            +'   <a href="javascript:;">'+(i)+'</a>'
            +'</li>';
    }
    //下一页
    _url = '';
    if(parseInt(json.page) + 1 <= listRows) _url = url.replace('__page__', parseInt(json.page) + 1).replace('__listRows__', json.listRows);
    li += '<li onclick="J_loade(this)" data-article="J_article" data-class="J_home" data-url="'+_url +'">'
        +'  <a href="javascript:;" aria-label="Next">'
        +'   <span aria-hidden="true">下一页</span>'
        +' </a>'
        +'</li>';
    $('.'+div).html(li);
}


var fdate = function(timeStamp) {
    var date = new Date();
    date.setTime(timeStamp * 1000);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
}

window.onload=function() {

    //添加字段
    $('.J_add_field').click(function () {
        var html = '<dl class="row">\n' +
            '                    <dt class="tit">\n' +
            '                        <label for="ac_sort"><input type="text" placeholder="字段名" name="fieldName[]"/></label>\n' +
            '                    </dt>\n' +
            '                    <dd class="opt">' +
            '                       <div class="J_item" ></div>' +
            '                       <select name="fieldType[]" style="width:150px;" onchange="J_file_type(this)">\n' +
            '                            <option value="">-- 请选择 --</option>\n' +
            '                            <option value="text">文本框</option>\n' +
            '                            <option value="select">下拉框</option>\n' +
            '                            <option value="textarea">文本域</option>\n' +
            '                            <option value="radio">单选按钮</option>\n' +
            '                            <option value="hidden">隐藏域</option>\n' +
            '                            <option value="file">上传图片</option>\n' +
            '                            <option value="checkbox">复选框</option>\n' +
            '                        </select>' +
            '                        <a href="javascript:;" onclick="J_del_div(this)" data-class="row">删除</a>' +
            '                        <input type="hidden" name="hidden[]" value="false">' +
            '                    </dd>\n' +
            '                </dl>';
        $('.J_field_content').append(html);
    });

    //自定义连接
    $('body').on('click', '.J_href', function () {
        var _url = $(this).attr('data-url');
        if (_url) window.location.href = _url;
    })

    //删除
    $('.J_del').click(function () {
        J_del(this);
    })

    //全选
    $('.J_ckbox').click(function () {
        $('.J_box').prop("checked", true);
    });

    //反选
    $('.J_unbox').click(function () {
        $('.J_box').prop('checked', false);
    });

    //选中 所有上级、下级选中
    $('.J_box').click(function () {
        var _this = $(this), val = _this.val(), checked=_this.prop("checked");

        //下级
        $("[one_key='"+val+"']").prop("checked", checked);
        $("[two_key='"+val+"']").prop("checked", checked);
        $("[three_key='"+val+"']").prop("checked", checked);

        //上级
        var one_key=_this.attr("one_key");
        var two_key=_this.attr("two_key");
        var three_key=_this.attr("three_key");
        if(checked) {//对一，二级权限选中
            $("[key="+one_key+"]").prop("checked",checked);
            $("[key="+two_key+"]").prop("checked",checked);
            $("[key="+three_key+"]").prop("checked",checked);
        }
    });

    //返回上一页
    $('.J_back').click(function () {
        history.back(-1);
    });

    //刷新页面
    $('.J_reload').click(function () {
        location.reload();
    });

    //鼠标移上
    $('.J_mouse_over').mouseover(function () {
        var _this = $(this),
            _class = _this.attr('data-class');
        if(_class == '' || _class == undefined) $(this).next().show(500);
        else $('.'+_class).show(100);
    });

    //鼠标移开
    $('.J_mouse_out').mouseleave(function () {
        var _this = $(this), _class = _this.attr('data-class');
        if(_class == '' || _class == undefined) $(this).hide(500);
        else $('.'+_class).hide(500);
    });

    //点击body事件
    $('body').click(function () {
        $('.J_mouse_out').hide(500);
    });

    //鼠标点击 显示 隐藏
    $('.J_click').click(function () {
        var _this = $(this), _class = _this.attr('data-class'), obj;
        if(_class == '' || _class == undefined) obj = $(this).next();
        else obj = $('.'+_class);
        obj.slideToggle(200);
        var change = _this.find('.J_change');
        if(change !== undefined) {
            change.toggleClass(change.attr('data-class'));
            change.html(change.attr('data-text-'+change.is(':visible').toString()));
        }
    });

    //ajax 加载
    $('.J_loade').click(function () {
        J_loade(this);
    });

    //留言模块
    $('.J_msg_submit').click(function(){
        var J_message = $(this).parents('.J_message');
        var name = J_message.find('#name').val();
        var name_msg = J_message.find('#name').attr('data-msg');

        var phone= J_message.find('#phone').val();
        var phone_msg = J_message.find('#phone').attr('data-msg');

        var email= J_message.find('#email').val();
        var email_msg = J_message.find('#email').attr('data-msg');

        var msg= J_message.find('#msg').val();
        var msg_msg = J_message.find('#msg').attr('data-msg');

        var event_id = J_message.find('#event_id').val();
        var uid= J_message.find('#uid').val();
        var type = J_message.find('#type').val();
        var show = $('#J_mini_modal').html();
        var show_msg = J_message.find('#show_msg').val();

        var pattern = /[A-Za-z0-9_\-\u4e00-\u9fa5]+/;
        if(name != undefined && pattern.test(name) == false) {
            show != undefined ? showMiniModal(name_msg == undefined ? '请填写正确的姓名!' : name_msg) : alert(name_msg == undefined ? '请填写正确的姓名!' : name_msg);
            return false;
        }
        pattern = /0?(13|14|15|18)[0-9]{9}/;
        if(phone != undefined && pattern.test(phone) == false){
            show != undefined  ? showMiniModal(phone_msg == undefined ? '请填写正确的手机号!' : phone_msg) : alert(phone_msg == undefined ? '请填写正确的手机号!' : phone_msg);
            return false;
        }

        pattern = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
        if(email != undefined &&  pattern.test(email ) == false) {
            show != undefined  ? showMiniModal(email_msg == undefined ? '请填写正确的邮箱!':email_msg) : alert(email_msg == undefined ? '请填写正确的邮箱!':email_msg);
            return false;
        }

        if(msg== '') {
            show != undefined ? showMiniModal(msg_msg == undefined ? '内容不能为空!' :msg_msg) : alert(msg_msg == undefined ? '内容不能为空!' :msg_msg);
            return false;
        }
        $.post('/index.php/Home/Message/send', {name:name,phone:phone,email:email,msg:msg,event_id:event_id,uid:uid,type:type}, function(json){
            show != undefined ? showMiniModal(show_msg == undefined ? json.msg : show_msg) : alert(show_msg == undefined ? json.msg : show_msg);
            //location.reload();
            if(typeof messageBack == "function"){
                html = messageBack(J_message, json);
            }
            }, 'json');
    });

    //分享到qq好友
    $('.J_share_qq').click(function () {
        var url = 'http://connect.qq.com/widget/shareqq/index.html',
            _url = $(this).attr('data-url'),
            desc = $(this).attr('data-desc'),
            title = $(this).attr('data-title'),
            summary = $(this).attr('data-summary'),
            pics = $(this).attr('data-pics'),
            flash = $(this).attr('data-flash'),
            site = $(this).attr('data-site'),
            callback = $(this).attr('data-callback');

        if(_url != undefined && _url != '') url += '?url='+_url;
        else url += '?url='+window.location.href;
        if(desc != undefined && desc != '') url += '&desc='+desc; //详情
        if(title != undefined && title != '') url += '&title='+title; //标题
        if(summary != undefined && summary != '') url += '&summary='+summary; //简介
        if(pics != undefined && pics != '') url += '&pics='+pics;   //图片
        if(flash != undefined && flash != '') url += '&flash='+flash;
        if(site != undefined && site != '') url += '&site='+site;   //邀请人或网站
        if(callback != undefined && callback != '') url += '&callback='+callback;
        window.open(url);
    });

    //分享到qq空间
    $('.J_share_qzone').click(function () {
        var url = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey',
            _url = $(this).attr('data-url'),
            title = $(this).attr('data-title'),//标题
            desc = $(this).attr('data-desc'),//详情
            summary = $(this).attr('data-summary'),//简介
            site = $(this).attr('data-site'),
            pics = $(this).attr('data-pics');//图片

        if(_url != undefined && _url != '') url += '?url='+_url;
        else url += '?url='+window.location.href;
        if(desc != undefined && desc != '') url += '&desc='+desc; //详情
        if(title != undefined && title != '') url += '&title='+title; //标题
        if(summary != undefined && summary != '') url += '&summary='+summary; //简介
        if(pics != undefined && pics != '') url += '&pics='+pics;   //图片
        if(site != undefined && site != '') url += '&site='+site;   //邀请人或网站
        window.open(url);
    });

    //微博
    $('.J_share_weibo').click(function () {
        var url = 'http://service.weibo.com/share/mobile.php',
            _url = $(this).attr('data-url'),
            title = $(this).attr('data-title'),//标题
            desc = $(this).attr('data-desc'),//详情
            summary = $(this).attr('data-summary'),//简介
            site = $(this).attr('data-site'),
            pics = $(this).attr('data-pics');//图片

        if(_url != undefined && _url != '') url += '?url='+_url;
        else url += '?url='+window.location.href;
        if(desc != undefined && desc != '') url += '&desc='+desc; //详情
        if(title != undefined && title != '') url += '&title='+title; //标题
        if(summary != undefined && summary != '') url += '&summary='+summary; //简介
        if(pics != undefined && pics != '') url += '&pic='+pics;   //图片
        if(site != undefined && site != '') url += '&site='+site;   //邀请人或网站
        window.open(url);
    });
}